import { defineStore } from "pinia"
import { ref } from "vue"
import { getMatcheSignalApi } from "@/pages/xinhaozhi/apis/index"
import type * as Football from "@/pages/xinhaozhi/apis/type"
import { toFixedFour } from "./utils"

interface OddsData {
  homeWin: number
  draw: number
  awayWin: number
  homeWinRate: string
  drawRate: string
  awayWinRate: string
  oddsTime: string
  signalHome: number | null
  signalDraw: number | null
  signalAway: number | null
}

export const useSignalStore = defineStore("signal", () => {
  // State
  const isLoadingSignals = ref(false)
  
  // 公司数据
  const company293Signals = ref<Football.Signal[]>([])
  const company18Signals = ref<Football.Signal[]>([])

  // 表格数据
  const leftTableData = ref<OddsData[]>([])
  const rightTableData = ref<OddsData[]>([])

  // Actions

  /** 处理公司数据 - 通用函数 */
  function processCompanyData(signals: Football.Signal[], isCompany293: boolean = true): OddsData[] {
    const sortedSignals = [...signals].sort((a, b) => {
      if (!a.odds_time || !b.odds_time) return 0
      return new Date(a.odds_time).getTime() - new Date(b.odds_time).getTime()
    })

    // 处理表格数据
    const tableData = sortedSignals.map((signal: Football.Signal) => ({
      homeWin: signal.home_odds,
      draw: signal.draw_odds,
      awayWin: signal.away_odds,
      homeWinRate: `${(signal.prob_home_odds * 100).toFixed(2)}%`,
      drawRate: `${(signal.prob_draw_odds * 100).toFixed(2)}%`,
      awayWinRate: `${(signal.prob_away_odds * 100).toFixed(2)}%`,
      oddsTime: signal.odds_time || '',
      signalHome: toFixedFour(signal.signal_home),
      signalDraw: toFixedFour(signal.signal_draw),
      signalAway: toFixedFour(signal.signal_away)
    }))

    // 赋值到对应的响应式变量
    if (isCompany293) {
      leftTableData.value = tableData
    } else {
      rightTableData.value = tableData
    }


    return tableData
  }

  /** 处理威廉希尔的数据 */
  function processCompany293Data(signals: Football.Signal[]) {
    company293Signals.value = signals
    return processCompanyData(signals, true)
  }

  /** 处理必发的数据 */
  function processCompany18Data(signals: Football.Signal[]) {
    company18Signals.value = signals
    return processCompanyData(signals, false)
  }

  /** 获取两个公司的信号数据 */
  async function fetchSignals(fid: number) {
    isLoadingSignals.value = true

    try {
      const [company293Response, company18Response] = await Promise.all([
        getMatcheSignalApi({ fid, company_id: 293 }),
        getMatcheSignalApi({ fid, company_id: 18 })
      ])

      if (company293Response.code === 0 && company293Response.data) {
        processCompany293Data(company293Response.data)
      } else {
        console.error("获取威廉希尔数据失败:", company293Response.message)
      }

      if (company18Response.code === 0 && company18Response.data) {
        processCompany18Data(company18Response.data)
      } else {
        console.error("获取必发数据失败:", company18Response.message)
      }

      return {
        company293Success: company293Response.code === 0 && !!company293Response.data,
        company18Success: company18Response.code === 0 && !!company18Response.data
      }

    } catch (error) {
      console.error("Failed to fetch signal data:", error)
      resetSignalData()
      return {
        company293Success: false,
        company18Success: false
      }
    } finally {
      isLoadingSignals.value = false
    }
  }

  /** 重置信号相关数据 */
  function resetSignalData() {
    company293Signals.value = []
    company18Signals.value = []
    leftTableData.value = []
    rightTableData.value = []
  }

  return {
    // 状态
    isLoadingSignals,
    company293Signals,
    company18Signals,
    leftTableData,
    rightTableData,
    
    // 方法
    fetchSignals,
    processCompany293Data,
    processCompany18Data,
    resetSignalData,
    toFixedFour
  }
})
